package com.mol.market.common.widget;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;

import android.content.Context;

import com.mol.market.Constants;
import com.mol.market.common.util.DBUtils;
import com.mol.market.common.util.Pair;
import com.mol.market.common.vo.LogEntity;

public class DefaultExceptionHandler implements UncaughtExceptionHandler {

	private UncaughtExceptionHandler defaultExceptionHandler;

	private Context context;

	public DefaultExceptionHandler(
			UncaughtExceptionHandler pDefaultExceptionHandler, Context context) {
		
		defaultExceptionHandler = pDefaultExceptionHandler;
		this.context = context;
	}
	
	@Override
	public void uncaughtException(Thread t, Throwable e) {

		final Writer result = new StringWriter();
		final PrintWriter printWriter = new PrintWriter(result);
		e.printStackTrace(printWriter);

		LogEntity entity = new LogEntity(context, Constants.MOBILE_CRASH,
				LogEntity.LOG_LEVEL_E);
		entity.addLogContent(new Pair<String, String>("exception", result
				.toString()));
		DBUtils.insertLog(context, entity);

		// call original handler
		defaultExceptionHandler.uncaughtException(t, e);
	}
}
